<template>
    <d2-container>
      <template slot="header">
        <div>
            <el-input clearable style="width:200px;" size="medium" v-model="listQuery.id" placeholder="订单编号-精确搜索"></el-input>
            <el-select clearable style="margin-left: 15px;" size="medium" v-model="listQuery.state" placeholder="请选择订单状态">
                <el-option
                    v-for="item in stateSelectOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                    <span style="float: left">{{ item.label }}</span>
                </el-option>
            </el-select>
            <el-input v-model="listQuery.user_id" clearable style="width:200px;margin-left: 15px;" size="medium" placeholder="用户编号-精确搜索"></el-input>
            <el-button style="margin-left: 15px;" type="primary" size="medium" @click="search()">搜索</el-button>
        </div>

      </template>
      <el-table
        :data="tableData"
        stripe
        border
        height="100%">
        <el-table-column prop="id" label="编码" width="80" header-align="center"></el-table-column>
        <el-table-column prop="create_time" label="创建日期" width="160" header-align="center"></el-table-column>
        <el-table-column prop="state" label="订单状态" width="140" header-align="center">
            <template slot-scope="scope">
                <el-tag :effect="statusTheme(scope.row)" :type="statusTagColor(scope.row)">{{statusFormatter(scope.row)}}</el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="receive_address" label="收货地址" width="320" header-align="center"></el-table-column>
        <el-table-column prop="user_id" label="用户编号" width="110" header-align="center"> </el-table-column>
        <el-table-column prop="remarks" label="备注" width="300" header-align="center" :formatter="remarksFormatter"></el-table-column>
        <el-table-column fixed="right" label="操作" width="235" header-align="center">
            <template slot-scope="scope">
                <el-button @click="openDetailDialog(scope.row)" type="success" size="small">查看详情</el-button>
                <el-button type="warning" size="small" @click="editOrder(scope.row)">修改</el-button>
                <el-popconfirm
                    title="将永久删除订单,用户将无法看到此订单，确定删除吗？"
                    @confirm="deleteOrder(scope.row)"
                    @cancel="cancelPop"
                >
                    <el-button slot="reference" type="danger" size="small" style="margin-left:10px;">删除</el-button>
                </el-popconfirm>
            </template>
        </el-table-column>
        </el-table>

        <!-- 修改订单弹窗 -->
        <el-dialog title="修改订单" :visible.sync="orderDialogFormVisible" @close="closeEdit">
            <el-form :model="orderForm" :label-position="'right'" label-width="80px">
                <el-form-item label="订单状态" label-width="600">
                    <el-select v-model="orderForm.state" placeholder="请选择订单状态">
                        <el-option
                            v-for="item in stateSelectOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                            :disabled="item.disabled">
                            <span style="float: left">{{ item.label }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="收货地址" label-width="600">
                    <el-cascader
                        style="width:250px;"
                        clearable
                        placeholder="请选择收货地区"
                        :options="addressOptions"
                        v-model="addressSelectedOptions"
                        @change="addressHandleChange">
                    </el-cascader>
                    <el-input style="width:350px;margin-left: 10px;" placeholder="详细地址" v-model="orderForm.receive_address" autocomplete="off"></el-input>
                    <el-input
                        clearable
                        style="width:87%;margin-left: 68px;margin-top: 20px;"
                        type="textarea"
                        placeholder="粘贴如：福建省厦门市集美区理工路600号厦门理工学院"
                        v-model="analysisAddress"
                        maxlength="80"
                        show-word-limit>
                    </el-input>
                    <el-row type="flex" justify="end">
                        <el-col :span="4">
                            <el-button type="danger" round size="mini" @click="analysis()">智能解析</el-button>
                        </el-col>
                    </el-row>

                </el-form-item>
                <el-form-item label="备注" label-width="600">
                    <el-input v-model="orderForm.remarks" autocomplete="off" style="width:500px;margin-left: 25px;" placeholder="请输入收货地址"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="orderDialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="sendUpdateRequest">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 订单详细信息弹窗 -->
        <el-dialog :visible.sync="detailDialogFormVisible" @close="onCloseDetail" title="订单详情" width="750px">
            <el-row :gutter="11" style="height:500px;overflow-y:scroll">
                <el-form ref="orderDetail" :model="orderDetail" size="medium" label-width="100px"
                label-position="left">
                    <el-col :span="12">
                        <el-form-item label="订单编号">
                        <el-input v-model="orderDetail.id" placeholder="请输入订单编号" readonly prefix-icon='el-icon-s-order'
                            :style="{width: '100%'}"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="创建时间">
                        <el-input v-model="orderDetail.create_time" placeholder="请输入创建时间" readonly
                            prefix-icon='el-icon-time' :style="{width: '100%'}"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label="下单用户账号" >
                        <el-input v-model="orderDetail.user" placeholder="请输入下单用户编码" readonly clearable
                            :style="{width: '50%'}"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label="订单状态">
                        <el-input v-model="orderDetail.state" placeholder="请输入订单状态" readonly
                            prefix-icon='el-icon-s-operation' :style="{width: '100%'}"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label="收货地址">
                        <el-input v-model="orderDetail.receive_address" type="textarea" placeholder="请输入收货地址" readonly
                            :autosize="{minRows: 2, maxRows: 2}" :style="{width: '100%'}">
                        </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label="备注">
                        <el-input v-model="orderDetail.remarks" type="textarea" placeholder="请输入备注" readonly
                            :autosize="{minRows: 2, maxRows: 2}" :style="{width: '100%'}"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col >
                        <el-form-item label="订单中商品" >
                            <el-card
                                style="margin-top:10px;"
                                :body-style="{ padding: '10px' }"
                                v-for="item in orderDetail.orderDetailList"
                                :key="item.id">
                                    <el-row>
                                        <el-col :span="5">
                                            <img style="width:100px;" :src="item.commodity.photo" class="image">
                                        </el-col>
                                        <el-col :span="19">
                                            <el-row>
                                                <span> {{item.commodity.name}}</span>
                                            </el-row>
                                            <el-row>
                                                <el-col :span="8">单价：{{item.commodity.price}} 元</el-col>
                                                <el-col :span="8">数量：{{item.number}}</el-col>
                                                <el-col :span="4">共￥{{item.commodity.price*item.number}}</el-col>
                                            </el-row>
                                        </el-col>
                                    </el-row>
                            </el-card>
                        </el-form-item>
                    </el-col>
                    <el-col :span="15">.</el-col>
                    <el-col :span="9">
                        <el-form-item label="订单总金额">
                            <span style="font-size: large;color:red">￥{{orderTotolMoney}}</span>
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-row>
        </el-dialog>
        <template slot="footer">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="listQuery.page"
                :page-sizes="[15, 30, 50, 100, 300, 500]"
                :page-size="listQuery.size"
                layout="total, sizes, prev, pager, next, jumper"
                :total="listTotal">
            </el-pagination>
        </template>
    </d2-container>
</template>

  <script>
  import AddressParse from 'address-parse';
  import {regionData,CodeToText, TextToCode} from 'element-china-area-data'
  import {request} from '@/api/service'
  export default {
    
    name: 'allOrder',
    methods: {
        remarksFormatter(row){
            if(row.remarks == undefined || row.remarks == ""){
                return "无"
            }
            else return row.remarks;
        },
        cancelPop(){

        },
        analysis(){
            const result = AddressParse.parse(this.analysisAddress);
            console.log(result);
            console.log(TextToCode);
            if(result[0].province.includes("省") && result[0].province!="" && result[0].city!="" && result[0].area!="") {
                this.addressSelectedOptions = TextToCode[result[0].province][result[0].city][result[0].area].code;
                this.orderForm.receive_address = result[0].details + "  " + result[0].name + "  " + result[0].mobile;
                this.addressArea = result[0].province+result[0].city+result[0].area;
            } else if(!result[0].province.includes("省") && result[0].province!="" && result[0].city!="" && result[0].area!="") {
                //直辖市，特殊处理
                this.addressSelectedOptions = TextToCode[result[0].province+"市"]["市辖区"][result[0].area].code;
                this.orderForm.receive_address = result[0].details + "  " + result[0].name + "  " + result[0].mobile;
                this.addressArea = result[0].city+result[0].area;
            } else {
                this.$notify.error({
                    title: '错误',
                    message: '解析失败，请填写完整地址！'
                });
            }
            this.analysisAddress = undefined;
        },
        deleteOrder(row){
            request({
                url: 'order/' + row.id,
                method: 'delete'
            }).then(res=>{
                this.$notify({
                    title: '成功',
                    message: '删除订单成功',
                    type: 'success',
                    duration: 1000
                });
                this.orderDialogFormVisible = false;
                this.getList();
            })
        },
        closeEdit(){
            this.addressArea = '';
            this.addressSelectedOptions = [];
            this.resetStateOptions();
        },
        openDetailDialog(row){
            this.detailDialogFormVisible = true;
            request({
                url: 'order/detail/' + row.id,
                method: 'get'
            }).then(res=>{
                this.orderDetail = res;
                this.orderDetail.state = this.statusFormatter(res);
                this.orderDetail.user = this.orderDetail.user.account
                this.orderTotolMoney = 0;
                this.orderDetail.orderDetailList.forEach(item=>{
                    this.orderTotolMoney += item.commodity.price * item.number;
                })
            })
        },
        onCloseDetail() {
          this.$refs['orderDetail'].resetFields()
        },
        closeDetail() {
          this.$emit('update:visible', false);
          this.detailDialogFormVisible = false;
        },
        handelConfirm() {
            
        },
        addressHandleChange(value){
            var address = ''
            value.map(item => address += CodeToText[item] + '/')
            this.addressArea = address.split('/').join('');
            console.log(this.addressSelectedOptions);
        },
        editOrder(row){
            this.orderDialogFormVisible = true;
            this.orderForm.id = row.id;
            this.orderForm.receive_address = row.receive_address;
            this.orderForm.state = parseInt(row.state);
            this.orderForm.remarks = row.remarks;
            
            const result = AddressParse.parse(this.orderForm.receive_address);
            if(result[0].province!="" && result[0].city!="" && result[0].area!="") {
                this.addressSelectedOptions = TextToCode[result[0].province][result[0].city][result[0].area].code;
                this.orderForm.receive_address = result[0].details + "  " + result[0].name + "  " + result[0].mobile;
            }
            
            this.addressArea = result[0].province+result[0].city+result[0].area;
            //限制修改
            for(let i=0;i<this.stateSelectOptions.length;i++){
                this.stateSelectOptions[i].disabled = true;
            }
            if(this.orderForm.state == 0) {
                this.stateSelectOptions[5].disabled = false;
                this.stateSelectOptions[0].disabled = false;
            } else if(this.orderForm.state == 1) {
                this.stateSelectOptions[2].disabled = false;
                this.stateSelectOptions[1].disabled = false;
            } else if(this.orderForm.state == 2) {
                this.stateSelectOptions[1].disabled = false;
                this.stateSelectOptions[2].disabled = false;
                this.stateSelectOptions[3].disabled = false;
            } else if(this.orderForm.state == -2) {
                this.stateSelectOptions[7].disabled = false;
                this.stateSelectOptions[6].disabled = false;
            }
        },
        sendUpdateRequest(){
            //计算收货地址
            let order = JSON.parse(JSON.stringify(this.orderForm));
            console.log("计算收货地址："+this.addressArea);
            order.receive_address = this.addressArea + order.receive_address;
            
            request({
                url: 'order',
                method: 'put',
                data:order
            }).then(res=>{
                this.$notify({
                    title: '成功',
                    message: '更新订单成功',
                    type: 'success'
                });
                this.orderDialogFormVisible = false;
                this.getList();
            })
        },
        handleSizeChange(val) {
            this.listQuery.size = val;
            this.getList();
        },
        handleCurrentChange(val) {
            this.listQuery.page = val;
            this.getList();
        },
        search() {
            this.getList();
        },
        getList(){
            request({
                url: 'order/page',
                method: 'get',        
                params:this.listQuery

            }).then(res=>{
                this.tableData = res.list;
                this.listTotal = res.total;
            })
        },
        statusTheme(row){
            switch(row.state) {
                case 0:
                case 2:
                case -2:
                    return "light"
                case 1:
                case 3:
                case 4:
                case -1:
                case -3:
                    return "dark" 
                
            }
        },
        statusTagColor(row){
            switch(row.state) {
                case 0:
                case 1:
                    return ""
                case 2:
                case 3:
                    return "warning" 
                case 4:
                    return "success" 
                case -1:
                    return "info" 
                case -2:
                case -3:
                    return "danger" 
                
            }
        },
        statusFormatter(row){
            switch(row.state){
                case 0:
                    return "已下单（待支付）" 
                case 1:
                    return "已支付（待发货）"
                case 2:
                    return "已发货（待收货）" 
                case 3:
                    return "已收货（待评价）" 
                case 4:
                    return "已评价" 
                case -1:
                    return "已取消" 
                case -2:
                    return "申请退单（待审核）" 
                case -3:
                    return "已退单" 
            }
        },
        resetStateOptions(){
            for(let i=0;i<this.stateSelectOptions.length;i++){
                this.stateSelectOptions[i].disabled = false;
            }
            this.stateSelectOptions[0].disabled = this.stateSelectOptions[4].disabled = this.stateSelectOptions[6].disabled = true;
        }
    },
    deleteOrder (row) {
      request({
        url: 'order/' + row.id,
        method: 'delete'
      }).then(res => {
        this.$notify({
          title: '成功',
          message: '删除订单成功',
          type: 'success'
        })
        this.orderDialogFormVisible = false
        this.getList()
      })
    },
    closeEdit () {
      this.addressArea = ''
      this.addressSelectedOptions = []
      this.resetStateOptions()
    },
    openDetailDialog (row) {
      this.detailDialogFormVisible = true
      request({
        url: 'order/detail/' + row.id,
        method: 'get'
      }).then(res => {
        this.orderDetail = res
        this.orderDetail.state = this.statusFormatter(res)
        this.orderDetail.user = this.orderDetail.user.account
        this.orderTotolMoney = 0
        this.orderDetail.orderDetailList.forEach(item => {
          this.orderTotolMoney += item.commodity.price * item.number
        })
      })
    },
    onCloseDetail () {
      this.$refs.orderDetail.resetFields()
    },
    closeDetail () {
      this.$emit('update:visible', false)
      this.detailDialogFormVisible = false
    },
    handelConfirm () {

    },
    addressHandleChange (value) {
      var address = ''
      value.map(item => address += CodeToText[item] + '/')
      this.addressArea = address.split('/').join('')
      console.log(this.addressSelectedOptions)
    },
    editOrder (row) {
      this.orderDialogFormVisible = true
      this.orderForm.id = row.id
      this.orderForm.receive_address = row.receive_address
      this.orderForm.state = parseInt(row.state)
      this.orderForm.remarks = row.remarks

      const result = AddressParse.parse(this.orderForm.receive_address)
      if (result[0].province != '' && result[0].city != '' && result[0].area != '') {
        this.addressSelectedOptions = TextToCode[result[0].province][result[0].city][result[0].area].code
        this.orderForm.receive_address = result[0].details + '  ' + result[0].name + '  ' + result[0].mobile
      }

      // 限制修改
      for (let i = 0; i < this.stateSelectOptions.length; i++) {
        this.stateSelectOptions[i].disabled = true
      }
      if (this.orderForm.state == 0) {
        this.stateSelectOptions[5].disabled = false
        this.stateSelectOptions[0].disabled = false
      } else if (this.orderForm.state == 1) {
        this.stateSelectOptions[2].disabled = false
        this.stateSelectOptions[1].disabled = false
      } else if (this.orderForm.state == 2) {
        this.stateSelectOptions[1].disabled = false
        this.stateSelectOptions[2].disabled = false
      } else if (this.orderForm.state == -2) {
        this.stateSelectOptions[7].disabled = false
        this.stateSelectOptions[6].disabled = false
      }
    },
    sendUpdateRequest () {
      // 计算收货地址
      const order = JSON.parse(JSON.stringify(this.orderForm))
      order.receive_address = this.addressArea + order.receive_address

      request({
        url: 'order',
        method: 'put',
        data: order
      }).then(res => {
        this.$notify({
          title: '成功',
          message: '更新订单成功',
          type: 'success'
        })
        this.orderDialogFormVisible = false
        this.getList()
      })
    },
    handleSizeChange (val) {
      this.listQuery.size = val
      this.getList()
    },
    handleCurrentChange (val) {
      this.listQuery.page = val
      this.getList()
    },
    search () {
      this.getList()
    },
    getList () {
      request({
        url: 'order/page',
        method: 'get',
        params: this.listQuery

      }).then(res => {
        this.tableData = res.list
        this.listTotal = res.total
      })
    },
    statusFormatter (row) {
      switch (row.state) {
        case 0:
          return '已下单（待支付）'
        case 1:
          return '已支付（待发货）'
        case 2:
          return '已发货（待收货）'
        case 3:
          return '已收货（待评价）'
        case 4:
          return '已评价'
        case -1:
          return '已取消'
        case -2:
          return '申请退单（待审核）'
        case -3:
          return '已退单'
      }
    },
    resetStateOptions () {
      for (let i = 0; i < this.stateSelectOptions.length; i++) {
        this.stateSelectOptions[i].disabled = false
      }
      this.stateSelectOptions[0].disabled = this.stateSelectOptions[4].disabled = this.stateSelectOptions[6].disabled = true
    },

      data () {
    return {
      analysisAddressResult: {}, // 解析获得地址信息
      analysisAddress: '', // 用户输入的地址信息
      addressArea: '',
      orderTotolMoney: 0,
      detailDialogFormVisible: false,
      orderDetail: {
        id: undefined,
        create_time: undefined,
        user: undefined,
        state: undefined,
        receive_address: undefined,
        remarks: undefined,
        orderDetailList: []
      },
      stateSelectOptions: [
        { label: '已下单（待支付）', value: 0, disabled: true },
        { label: '已支付（待发货）', value: 1 },
        { label: '已发货（待收货）', value: 2 },
        { label: '已收货（待评价）', value: 3 },
        { label: '已评价（完成）', value: 4, disabled: true },
        { label: '已取消（完成）', value: -1 },
        { label: '申请退单（待审核）', value: -2, disabled: true },
        { label: '已退单（完成）', value: -3 }
      ],
      addressSelectedOptions: [],
      addressOptions: regionData,
      addtions: {},
      orderForm: {
        id: undefined,
        state: undefined,
        receive_address: undefined,
        remarks: undefined
      },
      orderDialogFormVisible: false,
      listTotal: undefined,
      listQuery: {
        page: 1,
        size: 15,
        id: undefined,
        create_time: undefined,
        state: undefined,
        receive_address: undefined,
        user_id: undefined,
        remarks: undefined
      },
      tableData: []
    }
  },
  created () {
    this.getList()
  }
}
</script>
